package com.ruoyi.system.controller;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.domain.Activity;
import com.ruoyi.system.domain.ActivityMember;
import com.ruoyi.system.service.IActivityMemberService;
import com.ruoyi.system.service.IActivityService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Objects;

/**
 * 【请填写功能名称】Controller
 *
 * @author ruoyi
 * @date 2025-08-04
 */
@Api(tags = "ActivityMemberController模块")
@Controller
@RequestMapping("/system/member")
public class ActivityMemberController extends BaseController
{
    private String prefix = "system/member";

    @Autowired
    private IActivityService activityService;

    @Autowired
    private IActivityMemberService activityMemberService;

    @RequiresPermissions("system:member:view")
    @GetMapping()
    public String member()
    {
        return prefix + "/member";
    }

    /**
     * 查询【请填写功能名称】列表
     */
    @RequiresPermissions("system:member:list")
    @PostMapping("/list")
    @ApiOperation(value = "【活动成员】代码")
    @ResponseBody
    public TableDataInfo list(ActivityMember activityMember)
    {
        startPage();
        List<ActivityMember> list = activityMemberService.selectActivityMemberList(activityMember);
        return getDataTable(list);
    }

    /**
     * 导出【请填写功能名称】列表
     */
    @RequiresPermissions("system:member:export")
    @Log(title = "【活动成员导出】", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ApiOperation(value = "YYY代码")
    @ResponseBody
    public AjaxResult export(ActivityMember activityMember)
    {
        List<ActivityMember> list = activityMemberService.selectActivityMemberList(activityMember);
        ExcelUtil<ActivityMember> util = new ExcelUtil<ActivityMember>(ActivityMember.class);
        return util.exportExcel(list, "【请填写功能名称】数据");
    }

    /**
     * 新增【请填写功能名称】
     */
    @RequiresPermissions("system:member:add")
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    /**
     * 新增保存【请填写功能名称】
     */
    @RequiresPermissions("system:member:add")
    @Log(title = "【活动成员添加】", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ApiOperation(value = "YYY代码")
    @ResponseBody
    @Transactional(rollbackFor = Exception.class) // 事务控制：确保新增成员和更新人数原子性
    public AjaxResult addSave(ActivityMember activityMember)
    {
//        int rows = activityMemberService.insertActivityMember(activityMember);
//        // 2. 若新增成功，同步更新对应活动的已参加人数（joined + 1）
//        if (rows > 0) {
//            Long activityId = activityMember.getActivityId();
//            // 执行更新：使用SQL自增避免并发问题（推荐）
//            activityService.updateActivityJoined(activityId);
//        }

        // 1. 校验活动是否存在且未达人数上限
        Long activityId = activityMember.getActivityId();
        Activity activity = activityService.selectActivityById(activityId);
        if (activity == null) {
            return AjaxResult.error("活动不存在");
        }
        // 校验人数上限（若maxPeople为0则不限制）
        if (activity.getMaxPeople() > 0 && activity.getJoined() >= activity.getMaxPeople()) {
            return AjaxResult.error("活动人数已满，无法添加新成员");
        }

        // 2. 校验该用户是否已加入活动（避免重复添加，基于唯一键uk_user_act）
//        ActivityMember existMember = activityMemberService.insertActivityMember(activityId, activityMember.getUserId());
//        if (existMember != null) {
//            return AjaxResult.error("该用户已加入此活动");
//        }

        // 3. 自动填充创建时间（若前端未传）
//        if (activityMember.getCreateTime() == null) {
//            activityMember.setCreateTime(System.currentTimeMillis()); // 秒级时间戳
//        }

        // 4. 新增成员并同步更新活动参与人数
        int rows = activityMemberService.insertActivityMember(activityMember);
        if (rows > 0) {
            // 调用活动Service更新joined字段（+1）
            activityService.incrementJoined(activityId);
            return AjaxResult.success("添加成功，活动参与人数已更新");
        } else {
            return AjaxResult.error("添加失败");
        }
//        return toAjax(rows);
    }

    /**
     * 修改【请填写功能名称】
     */
    @RequiresPermissions("system:member:edit")
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Long id, ModelMap mmap)
    {
        ActivityMember activityMember = activityMemberService.selectActivityMemberById(id);
        mmap.put("activityMember", activityMember);
        return prefix + "/edit";
    }

    /**
     * 修改保存【请填写功能名称】
     */
//    @RequiresPermissions("system:member:edit")
//    @Log(title = "【活动成员编辑】", businessType = BusinessType.UPDATE)
//    @PostMapping("/edit")
//    @ApiOperation(value = "YYY代码")
//    @ResponseBody
//    public AjaxResult editSave(ActivityMember activityMember)
//    {
//        return toAjax(activityMemberService.updateActivityMember(activityMember));
//    }

//    /**
//     * 修改【请填写功能名称】
//     */
//    @RequiresPermissions("system:member:edit")
//    @GetMapping("/updateStatus/{id}")
//    public String updateStatus(@PathVariable("id") Long id, ModelMap mmap)
//    {
//        ActivityMember activityMember = activityMemberService.selectActivityMemberById(id);
//        mmap.put("activityMember", activityMember);
//        return prefix + "/updateStatus";
//    }
    /**
     * 修改保存活动成员（使用joinStatus=2表示取消报名，替代标记删除）
     */
    @RequiresPermissions("system:member:edit")
    @Log(title = "活动成员编辑", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ApiOperation("修改活动成员信息（含取消/恢复报名）")
    @ResponseBody
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult updateStatus(ActivityMember activityMember) {

        ActivityMember original = activityMemberService.selectActivityMemberById(activityMember.getId());
        if (original == null) {
            return AjaxResult.error("活动成员记录不存在");
        }

        // 0→2 取消报名
        if ("2".equals(activityMember.getJoinStatus()) && "0".equals(original.getJoinStatus())) {
            activityService.decrementJoined(original.getActivityId());
//            activityMemberService.updateActivityMemberStatus(original.getActivityId(), original.getUserId(), 2);
            activityMember.setJoinStatus("2");
            activityMemberService.updateActivityMemberStatus(activityMember);
            return AjaxResult.success();
        }

        // 2→0 恢复报名
        if ("0".equals(activityMember.getJoinStatus()) && "2".equals(original.getJoinStatus())) {
            Activity activity = activityService.selectActivityById(original.getActivityId());
            if (activity.getMaxPeople() > 0 && activity.getJoined() >= activity.getMaxPeople()) {
                return AjaxResult.error("活动人数已满，无法恢复报名");
            }
//            activityMemberService.updateActivityMemberStatus(original.getActivityId(), original.getUserId(), 0);
            activityMember.setJoinStatus("0");
            activityMemberService.updateActivityMemberStatus(activityMember);
            activityService.incrementJoined(original.getActivityId());
            return AjaxResult.success();
        }

        // 其余情况：仅普通字段更新
        return toAjax(activityMemberService.updateActivityMember(activityMember));
    }


//    /**
//     * 删除【请填写功能名称】
//     */
//    @RequiresPermissions("system:member:remove")
//    @Log(title = "【活动成员删除】", businessType = BusinessType.DELETE)
//    @PostMapping( "/remove")
//    @ApiOperation(value = "YYY代码")
//    @ResponseBody
//    public AjaxResult remove(String ids)
//    {
//        return toAjax(activityMemberService.deleteActivityMemberByIds(ids));
//    }

    /**
     * 删除活动成员（批量）
     */
    @RequiresPermissions("system:member:remove")
    @Log(title = "活动成员删除", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult remove(String ids) {
        Long[] idArray = Convert.toLongArray(ids);
        for (Long id : idArray) {
            ActivityMember member = activityMemberService.selectActivityMemberById(id);
            if (member == null) continue;

            // 只有“报名成功”才需要扣减
            if ("0".equals(member.getJoinStatus())) {
                activityService.decrementJoined(member.getActivityId());
            }
        }
        return toAjax(activityMemberService.deleteActivityMemberByIds(ids));
    }
}
